package com.learn.xueer.ui.activity

import android.content.Context
import android.graphics.Bitmap
import android.graphics.drawable.Drawable
import android.net.Uri
import android.os.Bundle
import android.text.TextPaint
import android.text.style.ClickableSpan
import android.view.View
import com.blankj.utilcode.util.ActivityUtils
import com.blankj.utilcode.util.SpanUtils
import com.learn.xueer.R
import com.learn.xueer.app.appViewModel
import com.learn.xueer.app.base.BaseActivity
import com.learn.xueer.app.ext.showDialogExt
import com.learn.xueer.app.util.CacheUtil
import com.learn.xueer.app.util.GlideEngine
import com.learn.xueer.data.bindadapter.CustomBindAdapter
import com.learn.xueer.databinding.ActivityPersonalInformationBinding
import com.learn.xueer.ui.viewmodel.MineViewModel
import com.luck.picture.lib.app.PictureAppMaster
import com.luck.picture.lib.basic.PictureSelector
import com.luck.picture.lib.config.PictureMimeType
import com.luck.picture.lib.config.SelectMimeType
import com.luck.picture.lib.entity.LocalMedia
import com.luck.picture.lib.interfaces.OnResultCallbackListener
import com.luck.picture.lib.utils.MediaUtils
import kotlinx.android.synthetic.main.activity_personal_information.tv_tip
import me.hgj.jetpackmvvm.util.ActivityMessenger
import me.hgj.jetpackmvvm.util.get
import java.io.File


/**
 * 个人信息
 */
class PersonDataActivity : BaseActivity<MineViewModel, ActivityPersonalInformationBinding>() {

    override fun initView(savedInstanceState: Bundle?) {
        mDatabind.viewmodel = mViewModel
        mDatabind.click = ProxyClick()
        var user = CacheUtil.getUser()
        mViewModel.userInfo.value = user
        val span = object : ClickableSpan() {
            override fun onClick(widget: View) {
                ActivityMessenger.startActivity<ContactServerActivity>(this@PersonDataActivity)
            }

            override fun updateDrawState(ds: TextPaint) {
                ds.color = resources?.getColor(R.color._0cb76c)!!
                ds.isUnderlineText = false
            }
        }

        SpanUtils.with(tv_tip).append("如有更改个人信息，注册账号等问题，").append("请联系客服")
            .setClickSpan(span)
            .setForegroundColor(resources?.getColor(R.color._0cb76c) ?: 0)
            .create()


    }


    inner class ProxyClick {
        fun back() {
            finish()
        }

        fun changePass() {
            ActivityMessenger.startActivityForResult(
                this@PersonDataActivity, ForgetActivity::class,
                "from" to "person"
            ) {
                if (it != null) {
                    val data = it.get<String>("data") ?: ""
                    if (data == "login") {
                        CacheUtil.clearAll()
                        ActivityUtils.startActivity(LoginActivity::class.java)
                        ActivityUtils.finishAllActivities()
                    }
                }
            }
        }

        fun changeMobile() {
            ActivityMessenger.startActivityForResult(
                this@PersonDataActivity, ChangeMobileActivity::class,
                "from" to "person"
            ) {
                if (it != null) {
                    val data = it.get<String>("data") ?: ""
                    if (data == "login") {
                        CacheUtil.clearAll()
                        ActivityUtils.startActivity(LoginActivity::class.java)
                        ActivityUtils.finishAllActivities()
                    }
                }
            }
        }

        fun myClass() {
            ActivityMessenger.startActivity<MyClassActivity>(
                this@PersonDataActivity,
                "schoolName" to "${
                    mViewModel.userInfo.value?.school?.name
                }", "grade" to "${
                    mViewModel.userInfo.value?.grade?.gradeName
                }"
            )
        }

        fun update() {
            showDialogExt({
                PictureSelector.create(this@PersonDataActivity)
                    .openCamera(SelectMimeType.ofImage())
                    .forResult(object : OnResultCallbackListener<LocalMedia> {
                        override fun onResult(p0: java.util.ArrayList<LocalMedia>) {
                            var media = analyticalSelectResults(p0)
                            showLoading()
                            appViewModel.lccal=media?.realPath?:""
                            mViewModel.uploadAvatarReq(File(media?.realPath)) {
                                mViewModel.updateProfile(it) {
                                   runOnUiThread {
                                       var value =mViewModel. userInfo.value
                                       value?.avatar = it
                                       mViewModel.userInfo.value = value
                                       CacheUtil.setUser(value)
                                       CustomBindAdapter.circleImageUrl(mDatabind.ivAvatar, media?.realPath?:"")
                                   }
                                }
                            }
                        }

                        override fun onCancel() {

                        }

                    })

            }, {
                PictureSelector.create(this@PersonDataActivity)
                    .openGallery(SelectMimeType.ofImage())
                    .setImageEngine(GlideEngine.createGlideEngine())
                    .forResult(object : OnResultCallbackListener<LocalMedia> {
                        override fun onResult(result: ArrayList<LocalMedia>) {
                            var media = analyticalSelectResults(result)
                            showLoading()
                            appViewModel.lccal=media?.realPath?:""
                            mViewModel.uploadAvatarReq(File(media?.realPath)) {
                                mViewModel.updateProfile(it){
                                    runOnUiThread {
                                        var value =mViewModel. userInfo.value
                                        value?.avatar = it
                                        mViewModel.userInfo.value = value
                                        CacheUtil.setUser(value)
                                        CustomBindAdapter.circleImageUrl(mDatabind.ivAvatar, media?.realPath?:"")
                                    }
                                }
                            }
                        }

                        override fun onCancel() {}
                    })

            })

        }
    }

    private fun analyticalSelectResults(result: ArrayList<LocalMedia>): LocalMedia? {
        var m: LocalMedia? = null
        for (media in result) {
            if (media.width == 0 || media.height == 0) {
                if (PictureMimeType.isHasImage(media.mimeType)) {
                    val imageExtraInfo = MediaUtils.getImageSize(this, media.path)
                    media.width = imageExtraInfo.width
                    media.height = imageExtraInfo.height
                } else if (PictureMimeType.isHasVideo(media.mimeType)) {
                    val videoExtraInfo = MediaUtils.getVideoSize(
                        PictureAppMaster.getInstance().appContext,
                        media.path
                    )
                    media.width = videoExtraInfo.width
                    media.height = videoExtraInfo.height
                }
            }
            m = media

        }
        return m
    }
}